<template>
	<view class="page" :style="popupStyleCom">
		<view class="header">
			<view class="search-box">
				<view class="input-box">
					<u-search placeholder="请输入省份或城市名(如:北京市/北京/bj/beijing)" :showAction="false"
						v-model="searchValue"></u-search>
					<!-- <input class="input" v-model="searchValue" placeholder="请输入省份或城市名(如:北京市/北京/bj/beijing" @blur="search" /> -->
				</view>
			</view>

			<view class="location-city">
				<view class="title">当前城市：<text class="tip">{{currentProvince}} {{currentCity}}</text></view>
				<view class="tip" style="display: flex;align-items: center;" @click="refresh"><u-icon color="#0E93D9"
						name="reload"></u-icon>刷新定位</view>
			</view>
			<view class="hot-city">
				<view class="title">热门城市</view>
				<view class="hot-city-list">
					<view class="hot-city-item" v-for="(item,index) in hotCity" :key="index"
						@click="hotCityClick(item.code)">
						{{ item.name }}
					</view>
				</view>
			</view>
		</view>
		<uni-city-list :options="list" :showSelect="false" @click="cityClick"></uni-city-list>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const _ = db.command;
	const $ = _.aggregate;

	var cache = {};

	const hotCityCacheKey = "uni-city-list.hotCity";

	import uniCityList from "@/components/uni-city-list/uni-city-list"
	import citiesJson from '@/cities.json';
	export default {
		components: {
			uniCityList
		},
		onLoad() {
			this.getCloudData();
			// 初始化当前城市
			// this.refresh()
			let hotCity = uni.getStorageSync(hotCityCacheKey);
			if (hotCity) {
				this.hotCity = hotCity;
			}
			const eventChannel = this.getOpenerEventChannel();
		},
		data() {
			return {
				searchValue: "",
				where: {},
				list: [],
				current: 0,
				tabList: [{
					name: '中国内地（大陆）',
				}, {
					name: '港澳台地区及海外',
				}],
				hotCity: [{
						code: "110100",
						name: "北京"
					},
					{
						code: "310100",
						name: "上海"
					},
					{
						code: "330100",
						name: "杭州"
					},
					{
						code: "440100",
						name: "广州"
					},
					{
						code: "440300",
						name: "深圳"
					},
					{
						code: "320100",
						name: "南京"
					},
					{
						code: "500100",
						name: "重庆"
					},
					{
						code: "510100",
						name: "成都"
					}
				],
				currentProvince: '',
				currentCity: ''
			}
		},
		methods: {
			changeTab() {},
			async refresh() {
				uni.showLoading({
					title: '定位中...'
				});

				// 直接尝试获取位置
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (data) => {
						uni.hideLoading();
						if (data.address) {
							this.currentProvince = data.address.province || '';
							this.currentCity = data.address.city || '';
							if (!this.currentCity && data.address.district) {
								this.currentCity = data.address.district;
							}
						} else {
							this.currentProvince = '';
							this.currentCity = '未知';
						}

						// 如果定位成功获取到了城市名称
						if (this.currentCity) {
							let cityInfo = {
								code: this._getCityCode(this.currentCity).code,
								name: this.currentCity
							}
						} else {
							let cityInfo = {
								code: null,
								name: '未知'
							}
						}

					},
					fail: (err) => {
						uni.hideLoading();
						// 根据错误信息判断是否是权限问题
						const errMsg = err.errMsg || err.message || '';
						const errCode = err.errCode || err.code || 0;

						// 判断是否为权限相关错误
						const isPermissionError =
							errCode === 1 || // 缺少定位权限
							errMsg.includes('缺少定位权限') ||
							errMsg.includes('定位服务没有开启') ||
							errMsg.includes('geolocation:12') ||
							errMsg.includes('authorization') ||
							errMsg.includes('permission');

						if (isPermissionError) {
							// 权限相关错误
							uni.showModal({
								title: '授权提示',
								content: '需要获取您的位置信息，请在设置中开启定位权限',
								showCancel: true,
							});
						} else {
							uni.showToast({
								title: '定位失败',
								icon: 'none'
							});
						}

						this.currentProvince = '';
						this.currentCity = '定位失败';
					}
				});
			},
			_getCityCode(name) {
				if (name) {
					// 首先精确匹配
					for (let i = 0; i < this.list.length; i++) {
						const group = this.list[i];
						if (group.value && Array.isArray(group.value)) {
							const city = group.value.find(item => item.name === name);
							if (city) {
								return city;
							}
						}
					}

					// 如果精确匹配没找到，尝试模糊匹配（去除市、县等后缀）
					const cleanName = name.replace(/市$|县$|区$|盟$|州$|地区$/, '');
					for (let i = 0; i < this.list.length; i++) {
						const group = this.list[i];
						if (group.value && Array.isArray(group.value)) {
							const city = group.value.find(item =>
								item.name.includes(cleanName) ||
								item.name.replace(/市$|县$|区$|盟$|州$|地区$/, '').includes(cleanName)
							);
							if (city) {
								return city;
							}
						}
					}
				}
			},
			_select(cityInfo) {
				// 同时通过全局事件总线发送数据
				uni.$emit('citySelected', cityInfo);
				uni.navigateBack();
			},
			search() {
				if (this.searchValue) {
					// 只有搜索的时候才可以搜索到县级市（因为县级市太多了，如果一开始就全部显示组件会卡住）
					this.where = {
						name: new RegExp(this.searchValue),
						type: _.in([1, 2])
					};
				} else {
					this.where = {};
				}
				this.getCloudData();
			},
			getWhere() {
				let {
					where = {}
				} = this;
				return {
					type: 1,
					...where
				}
			},
			// 获取云端数据
			async getCloudData() {
				this.list = citiesJson.data
			},
			cityClick(e) {
				let name = e.item.name;
				let cityInfo = this.getCityInfo({
					name
				});
				this._select(cityInfo);
			},
			hotCityClick(code) {
				let cityInfo = this.getCityInfo({
					code
				});
				this._select(cityInfo);
			},
			getCityInfo(obj = {}) {
				let {
					code,
					name
				} = obj;
				let list = [];
				this.list.map((item, index) => {
					list = list.concat(item.value);
				});
				let cityInfo = list.find((item) => {
					return (code && item.code == code) || (name && item.name == name);
				});
				return cityInfo;
			},
		},
		computed: {
			popupStyleCom() {
				let systemInfo = uni.getSystemInfoSync();
				let top = systemInfo.safeAreaInsets.top || 0;
				//console.log('systemInfo: ', systemInfo)
				return `height: ${systemInfo.windowHeight - top}px`;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		box-sizing: border-box;
		position: relative;

		.header {
			height: 216px;
			// background-color: #f8f8f8;
			position: fixed;
			top: calc(var(--status-bar-height));
			left: 0;

			.search-box {
				display: flex;
				padding: 10px;
				height: 30px;
				align-items: center;

				.close-box {}

				.input-box {
					flex: 1;

					.input {
						background-color: #ffffff;
						padding: 5px 20px;
						border-radius: 20px;
					}
				}
			}

			.location-city {
				display: flex;
				font-weight: 500 !important;
				justify-content: space-between;

				.tip {
					color: #0E93D9;
					font-size: 24rpx;
					font-weight: 500 !important;
				}
			}

			.hot-city,
			.location-city {
				padding: 10px;
				box-sizing: border-box;

				.title {
					color: #A5A5A5;
				}

				.hot-city-list {
					display: flex;
					flex-wrap: wrap;
					box-sizing: border-box;
					margin: 0 -5px;
					margin-top: 10px;
				}

				.hot-city-item {
					border: 1px solid #f8f8f8;
					background-color: #ffffff;
					width: calc(25% - 10px);
					height: 30px;
					margin: 5px;
					display: flex;
					box-sizing: border-box;
					justify-content: center;
					align-items: center;
				}
			}
		}
	}
</style>